import pandas as pd
import numpy as np


def overview_data_process(jsondata):
    """
    全局概览图数据转换
    { start_label5: […], start_label4: […], 
    start_label3: […], ... }
    """
    dataset = {}
    for k, v in jsondata.items():
        for i in v:
            if str(i['date']) in dataset:
                dataset[str(i['date'])].update({
                    'date': i['date'],
                    k: i['count']
                })
            else:
                dataset[str(i['date'])] = {'date': i['date'], k: i['count']}

    return dataset


def trendilization(data):
    """
    将目标数据转化为趋势线绘制所需的数据
    四分位法, 仅对一个维度数据处理, 数据的采样间隔为50ms
    :param : data: 
    :return:
    """
    # 将数据转化为pandas能处理的数据结构
    sample = 50  # 采样间隔
    df = pd.DataFrame(data)
    if len(df.dropna()) == 0:
        return None
    else:
        df = df.T.dropna()
        attrs = ['min', '25%', '50%', '75%', 'max', 'mean']
        result = []
        for i in range(0, len(df), sample):
            row = df.iloc[i, :].describe()[attrs]
            temp = {'row_id': i}
            temp.update(row.to_dict())
            result.append(temp)
        res_df = pd.DataFrame(result)
        res_df = res_df.set_index('row_id')
        res_df = res_df[attrs]
        return res_df.to_dict(orient='split')


def smooth_curve(queryset):
    def mean_smooth(data, view_size=50):
        columns = list(data[0].keys())
        feature_list = [key for key in columns if key != 'test_id']
        df = pd.DataFrame(data, columns=columns)

        value_list = pd.DataFrame()
        value_list['test_id'] = df['test_id']
        for i in feature_list:
            value_list[i] = df.loc[:, i].rolling(window=view_size, min_periods=1,
                                                 center=True).mean()

        return value_list.to_dict(orient='records')

    return mean_smooth(queryset)


def str_to_list(string):
    trim_str = string[1:-1]
    strlist = trim_str.split(',')
    
    return [float(s) for s in strlist]
